import React, {Component} from 'react';

class ErrorBoundary extends Component {

    state = {
        hasError: '' // 用于标示子组件是否产生错误
    }

    // 当ErrorBoundary组件子组件异常，会触发此方法，并携带错误信息
    static getDerivedStateFromError(error) {
        // 只适用于生产环境(开发环境展示后页面还是会异常)
        console.log(error);
        return {hasError: error}
    }

    render() {
        return (
            <div>
                <h2> I am Parent Component</h2>
                {this.state.hasError ? <h2>子组件异常（This is a Error ~）</h2> : <Child/>}
            </div>
        );
    }

}


class Child extends Component {
    //  错误的数据（错误边界-在上一级组件中处理）
    state = {
        /*users: [
            {id: '001', name: 'Anna', age: 23},
            {id: '002', name: 'Duo', age: 18},
            {id: '003', name: 'LiMei', age: 32}
        ]*/
        users: 'error_data'
    }

    render() {
        return (
            <div>
                <h2> I am Child Component</h2>
                {
                    this.state.users.map((user) => {
                        return <h4 key={user.id}>name: {user.name} || age: {user.age}</h4>
                    })
                }
            </div>
        );
    }
}

export default ErrorBoundary;